<?php

declare(strict_types=1);

namespace App\Controller\m1;

use Throwable;
use App\Helper\Log;
use App\Helper\Util;
use App\Helper\Common;
use App\Helper\Verify;
use Hyperf\DbConnection\Db;
use App\Constants\ReturnCode;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\Manager\AuthMiddleware;
use App\Service\OfficeService;
use GuzzleHttp\Client;

#[Controller]
#[Middleware(AuthMiddleware::class)]
class StaticController extends AbstractController
{
    #每日统计
    #[RequestMapping(path: "everyday", methods: "post")]
    public function everyday()
    {
        $device = $this->request->input('device', '');//设备
        $currentPage = $this->request->input('currentPage', 1);//当前页码
        $pageSize = $this->request->input('pageSize', 15);//每页记录条数

        $field = ["num"];
        if(!empty($device)){
            $field = [$device."_num as num"];
        }

        $where = [['type', '=', 'everyday']];
        $offset = ($currentPage - 1) * $pageSize;
        $columns = ['date','num','h5_num','applet_num','android_num','ios_num'];
        $tags = ['reg'];

        $query = Db::table('statis_record')
            ->select($columns)
            ->where($where)
            ->whereIn('tag', $tags)
            ->groupBy('date');
        $total = $query->count();
        $datas = $query->offset($offset)
            ->limit($pageSize)
            ->orderBy('date', 'desc')
            ->get()
            ->toArray();
        $return_list = [];
        if (!empty($datas)) {
            foreach ($datas as $data) {
                $reg_data = Db::table('statis_record')
                    ->select($field)
                    ->where([['date', '=', $data['date']],['tag', '=', "reg"]])
                    ->first();

                $return_list[] = [
                    'date'=>$data['date'],
                    'reg_num'=>!empty($reg_data['num'])?$reg_data['num']:0
                ];
            }
        }
        return $this->fmt_response(ReturnCode::deal_succ, '成功', ['total'=>$total, 'list'=>$return_list]);
    }
    #订阅统计
    #[RequestMapping(path: "sub", methods: "post")]
    public function sub()
    {
        $device = $this->request->input('device', '');//设备
        $currentPage = $this->request->input('currentPage', 1);//当前页码
        $pageSize = $this->request->input('pageSize', 15);//每页记录条数

        $field = ["num"];
        if(!empty($device)){
            $field = [$device."_num as num"];
        }

        $where = [['type', '=', 'sub']];
        $offset = ($currentPage - 1) * $pageSize;
        $columns = ['date','num','h5_num','applet_num','android_num','ios_num'];
        $tags = ['gzh_sub','gzh_unsub','gzh_realsub','gzh_totalsub','day_sub','msg_send','msg_hit'];

        $query = Db::table('statis_record')
            ->select($columns)
            ->where($where)
            ->whereIn('tag', $tags)
            ->groupBy('date');
        $total = $query->get()->count();
        $datas = $query->offset($offset)
            ->limit($pageSize)
            ->orderBy('date', 'desc')
            ->get()
            ->toArray();
        $return_list = [];
        if (!empty($datas)) {
            foreach ($datas as $data) {
                $summary = $this->getWxSummary($data['date']);
                $summarylate = $this->getWxCumulate($data['date']);
                $gsd_num = $summary['new_user'];
                $gud_num = $summary['cancel_user'];
                $gzh_realsub_data = $gsd_num-$gud_num;
                $gzh_totalsub_data = $summarylate;

                $day_sub_data = Db::table('user_sub')
                    ->where([
                        ['created_at', '>=', strtotime($data['date'])],
                        ['created_at', '<=', strtotime($data['date']." 23:59:59")],
                        ['status', '=', 1],
                        ['is_del', '=', 0]
                    ])
                    ->count();

                $msg_send_data = Db::table('user_push_log')
                    ->where([
                        ['push_time', '>=', strtotime($data['date'])],
                        ['push_time', '<=', strtotime($data['date']." 23:59:59")],
                        ['status', '=', 1]
                    ])
                    ->count();
                $msg_hit_data = Db::table('user_push_log')
                    ->where([
                        ['push_time', '>=', strtotime($data['date'])],
                        ['push_time', '<=', strtotime($data['date']." 23:59:59")],
                        ['status', '=', 1],
                        ['is_hit', '=', 1]
                    ])
                    ->count();
                $mhd_num = $msg_hit_data??0;
                $msd_num = $msg_send_data??0;
                if(empty($mhd_num) || empty($msd_num)){
                    $msg_hit_rate_data = "0%";
                }else{
                    $msg_hit_rate_data = bcdiv((string)$mhd_num, (string)$msd_num, 2);
                    $msg_hit_rate_data = bcmul($msg_hit_rate_data, "100")."%";
                }

                $return_list[] = [
                    'date'=>$data['date'],
                    'gzh_sub_num'=>!empty($gsd_num)?$gsd_num:0,
                    'gzh_unsub_num'=>!empty($gud_num)?$gud_num:0,
                    'gzh_realsub_num'=>!empty($gzh_realsub_data)?$gzh_realsub_data:0,
                    'gzh_totalsub_num'=>!empty($gzh_totalsub_data)?$gzh_totalsub_data:0,
                    'day_sub_num'=>!empty($day_sub_data)?$day_sub_data:0,
                    'msg_send_num'=>!empty($msg_send_data)?$msg_send_data:0,
                    'msg_hit_num'=>!empty($msg_hit_data)?$msg_hit_data:0,
                    'msg_hit_rate'=>!empty($msg_hit_rate_data)?$msg_hit_rate_data:"-",
                ];
            }
        }
        return $this->fmt_response(ReturnCode::deal_succ, '成功', ['total'=>$total, 'list'=>$return_list]);
    }
    /**
     * 获取用户增减数据
     * [getWxSummary description]
     * @param  [type] $date [description]
     * @return [type]       [description]
     */
    public function getWxSummary($date)
    {
        $wxconfig = config('wxconfig', []);
        $gzhconfig = $wxconfig['gzh']??[];
        $appid = $gzhconfig['appid']??NULL;
        $appsecret = $gzhconfig['appsecret']??NULL;

        $params = [
            "begin_date" => $date,
            "end_date" => $date
        ];

        $access_token = Util::getWxAccessToken($appid, $appsecret);
        $url = "https://api.weixin.qq.com/datacube/getusersummary?access_token=".$access_token;
        $client = new Client();
        $response = $client->request("post", $url, [
            'headers' => [
                'Content-Type'=>'application/json',
            ],
            'body' => json_encode($params)
        ]);
        $res = $response->getBody()->getContents();
        $log_info = [
            'params'=>$params,
            'result'=>$res
        ];
        $log_info = json_encode($log_info,JSON_UNESCAPED_UNICODE);
        Log::get("wx_get_wxsummary")->info($log_info);
        $userSummary = json_decode($res, true);
        $return_data = [
            'new_user' => 0,
            'cancel_user' => 0,
        ];
        if(!empty($userSummary['list'])){
            foreach ($userSummary['list'] as $item) {
                $return_data['new_user'] += $item['new_user'];
                $return_data['cancel_user'] += $item['cancel_user'];
            }
        }
        return $return_data;
    }
    /**
     * 获取累计数据
     * [getWxCumulate description]
     * @param  [type] $date [description]
     * @return [type]       [description]
     */
    public function getWxCumulate($date)
    {
        $wxconfig = config('wxconfig', []);
        $gzhconfig = $wxconfig['gzh']??[];
        $appid = $gzhconfig['appid']??NULL;
        $appsecret = $gzhconfig['appsecret']??NULL;

        $params = [
            "begin_date" => $date,
            "end_date" => $date
        ];

        $access_token = Util::getWxAccessToken($appid, $appsecret);
        $url = "https://api.weixin.qq.com/datacube/getusercumulate?access_token=".$access_token;
        $client = new Client();
        $response = $client->request("post", $url, [
            'headers' => [
                'Content-Type'=>'application/json',
            ],
            'body' => json_encode($params)
        ]);
        $res = $response->getBody()->getContents();
        $log_info = [
            'params'=>$params,
            'result'=>$res
        ];
        $log_info = json_encode($log_info,JSON_UNESCAPED_UNICODE);
        Log::get("wx_get_wxsummary")->info($log_info);
        $userSummary = json_decode($res, true);
        $return_data = $userSummary['list'][0]['cumulate_user'] ?? 0;
        return $return_data;
    }
}